package com.cdtu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdtu.dto.R;
import com.cdtu.entity.Comments;
import com.cdtu.entity.User;
import com.cdtu.service.CommentsService;
import com.cdtu.service.SightsService;
import com.cdtu.service.UserService;
import javafx.scene.input.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author : wzs
 * @Date : 2023/8/7 13:28
 * @Description : TODO 用来接收图片下载何保存本地的请求
 */
@RestController
@CrossOrigin
@RequestMapping("api/comments")
public class CommentsController {
    @Autowired
    CommentsService commentsService;

    @Autowired
    UserService userService;

    @Autowired
    SightsService sightsService;

    @PostMapping("/add")
    public R add(@RequestBody Comments comments){
        System.out.println(comments);
        comments.setPublishTime(new Date());
        comments.setPublishUsername(userService.getById(comments.getPublishUserid()).getName());
        comments.setSightName(sightsService.getById(comments.getSightId()).getName());
        commentsService.save(comments);
        return R.success();
    }

//    /list/tree
    @GetMapping("/list/tree")
    public R tree(@RequestParam long id){
        System.out.println("tree调用成功"+id);
        LambdaQueryWrapper<Comments> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Comments::getSightId,id).eq(Comments::getAnswerId,0);
        List<Comments> list = commentsService.list(wrapper);
        for (Comments comments : list) {
            sonComments(comments);
        }
        System.out.println(list);
        return R.success(list);
    }

    public void sonComments(Comments comments){
        List<Comments> list = commentsService.list();
        List<Comments> son=new ArrayList<>();
        for (Comments com : list) {
            if (com.getAnswerId()==comments.getId()){
                son.add(com);
                sonComments(com);
            }
        }
        comments.setCommentsList(son);
    }

    @GetMapping("/detail/{cid}")
    public R commentsDetail(@PathVariable("cid") long cid) {
        Comments comments=commentsService.getById(cid);
        return R.success(comments);
    }

    @GetMapping("/list/{pageNo}/{pageSize}")
    public R list(@PathVariable Integer pageNo,
                  @PathVariable Integer pageSize,
                  @RequestParam(required = false) String searchKey) {
        LambdaQueryWrapper<Comments> commentsWrapper=new LambdaQueryWrapper<>();
        commentsWrapper.like(searchKey != null && searchKey != "", Comments::getPublishUsername, searchKey);
        Page<Comments> page = commentsService.page(new Page<>(pageNo, pageSize), commentsWrapper);
        return R.success(page);
    }

//    listByUserId
    //查询登录用户的评论
    @GetMapping("/listByUserId/{pageNo}/{pageSize}")
    public R listByUserId(@PathVariable Integer pageNo,
                          @PathVariable Integer pageSize,
                          @RequestParam(required = false) long userId,
                          @RequestParam(required = false) String valueTime,
                          HttpSession session) throws ParseException {
        LambdaQueryWrapper<Comments> commentsWrapper=new LambdaQueryWrapper<>();
        commentsWrapper.eq(Comments::getPublishUserid,userId);
        System.out.println(valueTime);
        if (valueTime!=null && valueTime.length()!=0&&!"null".equals(valueTime)){
            String s = valueTime.split(",")[0];
            String substring1 = s.substring(0,s.length()-9);
            Date sd = parseGMT(substring1);
            String e = valueTime.split(",")[1];
            String substring2 = e.substring(0,s.length()-9);
            Date ed = parseGMT(substring2);
            commentsWrapper.lt(!ed.equals("0"),Comments::getPublishTime,ed);
            commentsWrapper.gt(!sd.equals("0"),Comments::getPublishTime,sd);
        }
        Page<Comments> page = commentsService.page(new Page<>(pageNo, pageSize), commentsWrapper);
        return R.success(page);
    }

    public static Date parseGMT(String strDate) throws ParseException {
        if (strDate != null && strDate.trim().length() > 0) {
            strDate = strDate.substring(4,24).replace(" ","/");
            strDate = strDate.replace("Jan","01");
            strDate = strDate.replace("Feb","02");
            strDate = strDate.replace("Mar","03");
            strDate = strDate.replace("Apr","04");
            strDate = strDate.replace("May","05");
            strDate = strDate.replace("Jun","06");
            strDate = strDate.replace("Jul","07");
            strDate = strDate.replace("Aug","08");
            strDate = strDate.replace("Sep","09");
            strDate = strDate.replace("Oct","10");
            strDate = strDate.replace("Nov","11");
            strDate = strDate.replace("Dec","12");
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy/HH:mm:ss");
            Date date = sdf.parse(strDate);
            return date;
        }
        return null;
    }

    @DeleteMapping("/delete/{cid}")
    public R deleteComments(@PathVariable("cid") long cid) {
        boolean remove = commentsService.removeById(cid);
        LambdaQueryWrapper<Comments> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Comments::getParentId, cid);
        commentsService.remove(wrapper);
        if (!remove) {
            return R.error("删除失败，请重新尝试");
        }
        return R.success("删除成功");
    }
}
